import React, { memo, useRef, useContext, useCallback } from 'react'
import TodoCtx from '../context'
import { ADD_ITEM } from '../constan'
import { updataTodo } from '../api/index'
export default memo(
    function TdInput() {
        const { todoDispatch } = useContext(TodoCtx)
        const inputRef = useRef(null)
        const addItem = useCallback(
            async () => {
                const val = inputRef.current.value.trim();
                if (val.length) {
                    const obj = {
                        id: Date.now(),
                        completed: false,
                        content: val
                    }
                    const res = await updataTodo(obj)
                    if (res.code === 200) {
                        todoDispatch({
                            type: ADD_ITEM,
                            payload: obj
                        })
                        inputRef.current.value = ''
                    }
                }
            }, []
        )

        return (
            <div className='header'>
                <input type="text" ref={inputRef} /> <button onClick={addItem}> 增加</button>
            </div>
        )
    }

)